/*******************************************************************************
 
 Copyright (c) 2009 Anshu Chimala
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
*******************************************************************************/

#import "ClippyController.h"
#import "ClippyAppDelegate.h"
#import "EditClipController.h"
#import <Carbon/Carbon.h>

#define INSTR(needle, haystack) ([[[haystack lowercaseString] componentsSeparatedByString:[needle lowercaseString]] count] > 1)

@implementation ClippyController

-(id)init {
	if(!(self = [super init])) return nil;
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(filter:) name:NSControlTextDidChangeNotification object:searchBar];
	return self;
}

-(IBAction)createNewClip:(id)sender {
	[titleText setStringValue:@""];
	NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
	[bodyText setString:[pasteBoard stringForType:NSStringPboardType] ?: @""];
	[NSApp beginSheet:addPanel modalForWindow:mainPanel modalDelegate:nil didEndSelector:nil contextInfo:nil];
	[addPanel makeFirstResponder:titleText];
}

-(IBAction)deleteClip:(id)sender {
	if([tableView numberOfSelectedRows] <= 0) return;
	NSAlert *al = [NSAlert alertWithMessageText:@"Are you sure you want to delete the selected clipping?" defaultButton:@"Yes" alternateButton:@"No" otherButton:nil informativeTextWithFormat:@"The clipping will be deleted immediately and permanently."]; 
	[al beginSheetModalForWindow:mainPanel modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
	if(returnCode == 1) {
		int i=0;
		NSDictionary *ret = nil;
		NSMutableArray *clippings = [ClippyAppDelegate sharedClippyAppDelegate].clippings;
		for(NSDictionary *dict in clippings) {
			if(INSTR([searchBar stringValue], [dict objectForKey:@"title"]))
				i++;
			else if(INSTR([searchBar stringValue], [dict objectForKey:@"body"]))
				i++;
			if(i-1 == [tableView selectedRow]) {
				ret = dict;
				break;
			}
		}
		if(ret != nil)
			[[ClippyAppDelegate sharedClippyAppDelegate].clippings removeObject:ret];
		[[ClippyAppDelegate sharedClippyAppDelegate] synchronizeClippings];
	}
	[tableView reloadData];
}

-(void)copy:(id)sender {
	if([tableView numberOfSelectedRows] <= 0 || [[searchBar stringValue] length] <= 0) return;
	int rowIndex = [[tableView selectedRowIndexes] firstIndex];
	
	NSArray *clippings = [ClippyAppDelegate sharedClippyAppDelegate].clippings;
	NSDictionary *ret = nil;
	
	if([[searchBar stringValue] length] <= 0)
		ret = [clippings objectAtIndex:rowIndex];
	else {
		int i=0;
		for(NSDictionary *dict in clippings) {
			if(INSTR([searchBar stringValue], [dict objectForKey:@"title"]))
				i++;
			else if(INSTR([searchBar stringValue], [dict objectForKey:@"body"]))
				i++;
			if(i-1 == rowIndex) {
				ret = dict;
				break;
			}
		}
	}
	
	if(ret) {
		NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
		[pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
		[pasteBoard setString:[ret objectForKey:@"body"] forType:NSStringPboardType];
	}
	
	[searchBar setStringValue:@""];
	[tableView reloadData];
	
	[mainPanel performClose:nil];
}

-(void)filter:(id)sender {
	[tableView reloadData];
	[tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
	BOOL x = [tableView numberOfSelectedRows]>0 && [[searchBar stringValue] length]>0;
	[newButton setHidden:x];
	[editButton setHidden:!x];
}

#pragma mark table view

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView {
	NSArray *clippings = [ClippyAppDelegate sharedClippyAppDelegate].clippings;
	if([[searchBar stringValue] length] <= 0)
		return [clippings count];
	int i=0;
	for(NSDictionary *dict in clippings) {
		if(INSTR([searchBar stringValue], [dict objectForKey:@"title"]))
			i++;
		else if(INSTR([searchBar stringValue], [dict objectForKey:@"body"]))
			i++;
	}
	return i;
}

- (id)tableView:(NSTableView *)table objectValueForTableColumn:(NSTableColumn *)col row:(NSInteger)rowIndex {
	NSArray *clippings = [ClippyAppDelegate sharedClippyAppDelegate].clippings;
	if([[searchBar stringValue] length] <= 0)
		return [[clippings objectAtIndex:rowIndex] objectForKey:[col identifier]];
	else {
		int i=0;
		for(NSDictionary *dict in clippings) {
			if(INSTR([searchBar stringValue], [dict objectForKey:@"title"]))
				i++;
			else if(INSTR([searchBar stringValue], [dict objectForKey:@"body"]))
				i++;
			if(i-1 == rowIndex)
				return [dict objectForKey:[col identifier]];
		}
	}
	return @"ERROR";
}

#pragma mark Window

- (BOOL)windowShouldClose:(id)sender {
	[mainPanel.animator setAlphaValue:0];
	[mainPanel orderOut:nil];
	[NSApp hide:mainPanel];
	[NSApp unhideWithoutActivation];
	return NO;
}

-(IBAction)editClip:(id)x {
	int i=0;
	NSDictionary *ret = nil;
	NSMutableArray *clippings = [ClippyAppDelegate sharedClippyAppDelegate].clippings;
	for(NSDictionary *dict in clippings) {
		if(INSTR([searchBar stringValue], [dict objectForKey:@"title"]))
			i++;
		else if(INSTR([searchBar stringValue], [dict objectForKey:@"body"]))
			i++;
		if(i-1 == [tableView selectedRow]) {
			ret = dict;
			break;
		}
	}
	if(ret != nil)
	[editTitleText setStringValue:[ret valueForKey:@"title"]];
	[editBodyText setString:[ret valueForKey:@"body"]];
	[EditClipController sharedEditClipController].index = [clippings indexOfObject:ret];
	[NSApp beginSheet:editPanel modalForWindow:mainPanel modalDelegate:nil didEndSelector:nil contextInfo:nil];
	[addPanel makeFirstResponder:titleText];
}

@end
